#include "TextInput.h"

TextInput::TextInput()
{
    //初始化字符串
    str = "";
    
    //初始化表面
    text = NULL;

    x = 0;
    y = 0;

    textColor.r = 255;
    textColor.g = 255;
    textColor.b = 255;
    
    //启用Unicode
    SDL_EnableUNICODE( SDL_ENABLE );
}
 
TextInput::~TextInput()
{
    //释放文本表面
    SDL_FreeSurface( text );
    
    //禁用Unicode
    SDL_EnableUNICODE( SDL_DISABLE );  
}

void TextInput::handle_input(SDL_Event event)
{

    //如果一个按键被按下
    if( event.type == SDL_KEYDOWN )
    {
        //复制当前版本的字符串
        std::string temp = str;
        
        if( event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9 )
        {
            //在字符串末尾添加这个字符
            str += event.key.keysym.sym - SDLK_0 + '0';
        }

        if( event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z )
        {
            //在字符串末尾添加这个字符
            str += event.key.keysym.sym - SDLK_a + 'a';
        }
        if( str != temp )
        {
            if( text != NULL )
            {
                //释放旧的文本表面
                SDL_FreeSurface( text );
            }
            
            if( font != NULL )
            {
                //渲染一个新的文本表面
                text = TTF_RenderText_Solid( font, str.c_str(), textColor );
            }
        }
    }
}

void TextInput::show(SDL_Surface *screen)  
{
    //如果表面不是空的
    if( text != NULL )
    {
        //显示姓名
        SDL_Rect offset;
        offset.x = x;
        offset.y = y;

        SDL_BlitSurface( text, NULL, screen, &offset );
    }
}


void TextInput::setFont(TTF_Font *font)
{
    this->font = font;
}


void TextInput::setFontColor(unsigned char r, unsigned char g, unsigned char b)
{
    textColor.r = r;
    textColor.g = g;
    textColor.b = b;
}
